<?php

namespace App\Jobs;

use App\Models\Order;
use App\Services\IntegralLogService;
use App\Services\IntegralSetService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

/**
 * Class ShopIntegralJob
 * @package App\Jobs
 * 2021/3/16 - 16:51
 * Administrator
 * 03
 */
class ShopIntegralJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    //队列链接方式

    public $data = [];

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($data)
    {
        //
        $this->data = $data;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try {
            \DB::beginTransaction();
            $order_model = new Order();
            $order_list = $order_model->whereIn('id', $this->data['order_ids'])->with(['store' => function ($query) {
                return $query->select('id', 'class_id');
            }])->get();
            $log = new IntegralLogService();
            $integralService = new IntegralSetService();
            foreach ($order_list as $v) {
                $id = 0;
                $integral = 0;
                if (isset($this->data['cllback'])) {
                    $integral = $v['use_integral'];
                } else {
                    //赠送积分获取
                    extract($integralService->get_integral($v['store']['id'], $v['store']['class_id'], $this->data['scenes_type']), EXTR_OVERWRITE);
                }
                $reward = $this->data['reward'] . ',' . $integral . '积分';
                //积分日志
                $log->setLog($v['user_id'], $reward, $v['store']['id'], $id, $this->data['type'], $integral, $v['id']);
            }
            \DB::commit();
        } catch (\Exception $exception) {
            \DB::rollBack();
            $this->release(5);
        }
    }
}
